import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { ipcRenderer } from 'electron'
import { BarTitle, NewProject } from '../main/type'

// Custom APIs for renderer
const api = {
  controlFrame(value: boolean) {
    ipcRenderer.send('controlFrame', value)
  },
  openMain() {
    ipcRenderer.send('openMain')
  },
  setBarTitle(value: BarTitle) {
    ipcRenderer.send('setBarTitle', value)
  },
  //选择目录
  selectDirectory: () => {
    return ipcRenderer.invoke('selectDirectory')
  },
  // 下载模版
  downloadViteTemplate: (value: NewProject) => {
    return ipcRenderer.send('downloadViteTemplate', value)
  },
  projectTree: () => {
    return new Promise((resolve) => {
      ipcRenderer.on('projectTree', (_event, arg) => {
        resolve(arg)
      })
    })
  },
  fileValueByPath: (path: string) => {
    return ipcRenderer.send('fileValueByPath', path)
  },
  readFile: () => {
    return new Promise((resolve) => {
      ipcRenderer.on('readFile', (_event, arg) => {
        resolve(arg)
      })
    })
  },
  saveFile: (value: { path: string; content: string }) => {
    ipcRenderer.send('saveFile', value)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
